package algorithm.hashTable;

import java.util.List;

/**
 * 使用数组加链表的方式实现
 */
public class MyHashTable {
    public static void main(String[] args) {
        Hash hashTable = new Hash(5);
        Element e1 = new Element(2, "zjComing");
        Element e2 = new Element(45, "beijing");
        Element e3 = new Element(12, "ttttttt");
        Element e4 = new Element(60, "mmmmmmm");
        hashTable.add(e1);
        hashTable.add(e2);
        hashTable.add(e3);
        hashTable.add(e4);
        hashTable.show();
    }

}

//节点类
class Element {
    int id;
    String name;
    Element next;

    public Element(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

//数组中的每个元素，链表的头结点
class ElemLinkedList {
    Element head;

    //添加成员 添加到最后一个成员
    public void add(Element e) {
        if (head == null) {
            head = e;
            return;
        }
        Element temp = head;

        while (true) {
            if (temp.next == null) {
                break;
            }
            temp = temp.next;
        }
        temp.next = e;
    }

    public void show(int no) {
        Element temp = head;
        while (temp != null) {
            System.out.printf("第 %d 个链表=> id是：%d 姓名：%s\t", no + 1, temp.id, temp.name);
            temp = temp.next;
        }
        System.out.println();
    }
}

//hash表
class Hash {
    private ElemLinkedList[] list;
    private int size;

    public Hash(int size) {
        this.size = size;
        list = new ElemLinkedList[size];
        for (int i = 0; i < size; i++) {
            list[i] = new ElemLinkedList();
        }
    }

    //添加函数
    public void add(Element e) {
        int no = getNo(e.id);
        list[no].add(e);
    }

    public void show() {
        for (int i = 0; i < size; i++) {
            list[i].show(i);
        }
    }

    //hash函数
    private int getNo(int id) {
        return id % size;
    }
}